/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmContractController
 * 项目合同
 * <p>
 * 修改纪录
 * 2020-05-16 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-16
 */

package com.topscomm.pm.controller;

import com.alibaba.fastjson.JSONArray;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.ltc.service.ILtcChanceBackboneService;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.service.IMmsDeptExtraInfoService;
import com.topscomm.pm.controller.auto.PmContractControllerAuto;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.TapSystemConst;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: wushenghong
 * @date: 2020-05-16
 * @description:项目合同Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/contract")
public class PmContractController extends PmContractControllerAuto implements IPmContractController {
    @Autowired
    private ILtcChanceBackboneService chanceBackboneService;
    @Resource
    private IMmsDeptExtraInfoService deptExtraInfoService;


    /**
     * @author: wushenghong
     * @date: 2020-05-16
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" PmContract.enabled=1 ");
        if (paraMap.containsKey("qry_contractname")) {
            String value = paraMap.get("qry_contractname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.contractname like '%{0}%'", value);
        }
//        if (paraMap.containsKey("qry_projectname")) {
//            String value = paraMap.get("qry_projectname").toString();
//            if (!StringUtil.isEmpty(value))
//                sql.appendSingle(" and projectid = (select id from pmproject where name = '{0}') ", value);
//        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.state={0}", value);
        }
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.projectid = {0} ", value);
        }
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.docno like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_deptname")) {
            String value = paraMap.get("qry_deptname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (PmContract.deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (PmContract.username like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.deptcode like '{0}%'", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmContract.state={0}", value);
        }
        if (paraMap.containsKey("qry_where")) {
            String value = paraMap.get("qry_where").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0}", value);
        }
        sql .appendSingle(this.spellingSqlForProject(paraMap, "PmContract","projectid","id"));

        if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
        {
            String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", this.getUserBean());
            if (StringUtil.isEmpty(dataPession)) {
                sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
                        this.getUserBean().getUser(), "projectid",
                        service.getDao().getTableName()) +
                                " or PmContract.usercode = '{0}')",
                        this.getUserBean().getUser().getCode());
            }  else// 使用数据权限
            {
                sql.appendSingle(" and {0} ", dataPession);
            }
        }
        return sql.toString();
    }


    /**
     * @author: wushenghong
     * @date: 2020-05-16
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }
    // 取消审批
    @DeleteMapping({"/delApproval"})
    public ResponseResult<Object> delApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
        ResponseResult responseResult = super.delApproval(paraMap);
        if(responseResult.isSuccess()){
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            this.service.updateContractMoneyOfProjectBaseForApproval(id, false);
            return ResponseResult.ok("取消审批成功");
        }
        return responseResult;
    }

    /**
     *
     * @description: 提交审批前
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @author: wushenghong
     * @date: 2020-05-16
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交项目合同申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
        List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmContract", dataMap.get("deptcode").toString(),dataMap.get("usercode").toString(),null, "sortcode");
        Long flowid = flowidList.size()>0? ConvertUtil.convertToLong(flowidList.get(0).get("id")) :null;
        dataMap.put("flowid", flowid);
    }

    @Override
    @GetMapping({"/list"})
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            paraMap.put("whereSql",sqlWhere);
            int totalCount = this.service.getCount(paraMap,"getContractAndProjectCount");
            List<Map<String, Object>> tempList = null;
            HashMap<String, Object> paraMap2 = new HashMap<>();
            paraMap2.put("curPageIndex",query.getCurrentPage());
            int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
            paraMap2.put("begincount",beginCount);
            paraMap2.put("pagesize", query.getPageSize());
            paraMap2.put("sidx", query.getSidx());
            paraMap2.put("sord", query.getSord());
            paraMap2.put("whereSql", sqlWhere);
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(paraMap2,"getContractAndProject");
            } else {
                tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
            }
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    @Override
    @PutMapping(value = "/update")
    public ResponseResult<Object> update(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            Map<String, Object> dataMap = paraMap;
            //  判断是否为经营管理部初审节点，如果是经营管理部初审节点，因为供应链审批为多人需要转换，所以在后台进行处理
            if(dataMap.containsKey("CSApproval")){
                // 是经营管理部初审节点
                JSONArray Array = (JSONArray) dataMap.get("approvaldepartment");
                String initialdeptcode = ConvertUtil.convertToString(dataMap.get("deptcode"));
                String deptcode;
                // 26开始的为科远单据，科远的单据直接用initialdeptcode
                if(!initialdeptcode.startsWith("26")){
                    // 获取单据所在的一级部门
                    if(initialdeptcode.contains("_")){
                        // 四川、重庆、股份北京等分公司
                        deptcode = initialdeptcode.substring(0,initialdeptcode.indexOf('_')+5);
                    }else{
                        // 除分公司外的其他组织
                        deptcode = initialdeptcode.substring(0,4);
                    }
                }else{
                    deptcode=initialdeptcode;
                }
                final String[] approvalUserCode = new String[1];
                List departmentList = Array;
                StringBuffer usercodes = new StringBuffer();
                // 供应链审批，转换为单据所属省区对应的审批人
                if(departmentList.stream().anyMatch(item->item.equals("GYLSP"))){
                    List<Map<String, Object>> approvalDepartmentList = datacodeCache.getCodeListMap("ApprovalDepartmentUserCode", "", "sortcode");
                    approvalDepartmentList.stream().forEach(t->{
                        if(ConvertUtil.convertToString(t.get("name")).contains(deptcode+",")){
                            approvalUserCode[0]= ConvertUtil.convertToString(t.get("code"));
                        }
                    });

                    usercodes.append(',').append(approvalUserCode[0]).append(',');
                    for(Object item:departmentList){
                        if(item.equals("GYLSP")){
                            continue;
                        }else{
                            usercodes.append(item).append(',');
                        }
                    }
                }else{
                // 没有选择供应链，直接拼接
                    usercodes.append(',');
                    for(Object item:departmentList){
                        usercodes.append(item).append(',');
                    }
                }
                dataMap.remove("approvaldepartment");
                dataMap.remove("deptcode");
                dataMap.remove("CSApproval");
                dataMap.put("approvaldepartmentusercode",usercodes.toString());
            }
            beforeUpdate(dataMap, paraMap);
            this.service.update(dataMap);
            afterUpdate(dataMap, paraMap);
            return ResponseResult.ok("修改成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }


    @Override
    protected void afterLoad(Map<String, Object> paraMap) {
        super.afterLoad(paraMap);
        // 添加可修改审批后单据信息的人员code系统参数
        paraMap.put("modifyzhangqiusercode", ParameterCache.getValue("modifyzhangqiusercode"));
    }
    @GetMapping({"/queryContractByChance"})
    public ResponseResult<Object> queryContractByChance(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> contractList = this.service.queryContractByChance(paraMap);
            return ResponseResult.ok(contractList);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    @GetMapping({"/queryContractPhaseByChance"})
    public ResponseResult<Object> queryContractPhaseByChance(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> contractList = this.service.queryContractPhaseByChance(paraMap);
            return ResponseResult.ok(contractList);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }
    /**
     * @description:查询机会点参照列表
     * @param paraMap
     * @return
     * @author: 杜泽厚
     * @date: 2022-12-12
     * @modify:
     */

    @GetMapping(value = "/chanceSelectRefList")
    public ResponseResult<Object> chanceSelectRefList(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            StringBufferProxy sqlWhere = new StringBufferProxy();
            //同一级部门下有效且进展阶段为“谈判和生成合同”的机会点
            sqlWhere.appendSingle("1=1 and enabled = 1  and currentphase = '4' ");
            String deptcode = this.getUserBean().getDept().getCode();
            String deptCommonCode = deptExtraInfoService.getDeptCommonCode(deptcode);
            if (deptCommonCode!=null){
                sqlWhere.appendSingle(" and deptcommoncode1 = '{0}'",deptCommonCode);
            } else {
                sqlWhere.appendSingle(" and 1!=1 ");
            }
            //机会点名称
            if(paraMap.containsKey("qry_chancename")) {
                String value = paraMap.get("qry_chancename").toString();
                if (!StringUtil.isEmpty(value)){
                    sqlWhere.appendSingle(" and projectname like '%{0}%'", value);
                }
            }
            //机会点编号
            if (paraMap.containsKey("qry_chancecode")) {
                String value = paraMap.get("qry_chancecode").toString();
                if (!StringUtil.isEmpty(value)){
                    sqlWhere.appendSingle(" and code like '%{0}%' ", value);
                }
            }
            //负责人姓名或工号
            if (paraMap.containsKey("qry_user")) {
                String value = paraMap.get("qry_user").toString();
                if (!StringUtil.isEmpty(value)){
                    sqlWhere.appendSingle(" and (gardenercode = '{0}' or gardenername like '%{0}%')", value);
                }
            }
            //客户姓名
            if (paraMap.containsKey("qry_clientname")) {
                String value = paraMap.get("qry_clientname").toString();
                if (!StringUtil.isEmpty(value)){
                    sqlWhere.appendSingle(" and clientname like '%{0}%'", value);
                }
            }
            int totalCount = chanceBackboneService.getCount(sqlWhere.toString());
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = chanceBackboneService.queryMapForPagePM(sqlWhere.toString(), query.getCurrentPage(), query.getPageSize(),
                        query.getSidx(), query.getSord());
            } else
                tempList = chanceBackboneService.queryMapForPagePM(sqlWhere.toString(), query.getCurrentPage(), query.getPageSize(),
                        query.getSidx(), query.getSord());
            chanceBackboneService.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }
}

